//
//  DKLoginViewController.m
//  DanKU
//
//  Created by 吴斌 on 2023/9/19.
//

#import "DKLoginViewController.h"
#import "DKLoginForgetPwdViewController.h"
#import "DKRegisterViewController.h"

#import "DKLoginRegisterNameView.h"
#import "DKLoginPwdLoginView.h"
#import "DKLoginCodeLoginView.h"
//#import "DKLoginPhoneView.h"
#import "DKLoginChangeLoginTypeView.h"
#import "DKLoginAgreementAlertView.h"
#import "DKTabBarViewController.h"

#import "DKULoginHttp.h"
@interface DKLoginViewController ()<TTTAttributedLabelDelegate>
@property (nonatomic, strong)DKLoginPwdLoginView * dk_LoginPwdLoginView;
@property (nonatomic, strong)DKLoginCodeLoginView * dk_LoginCodeLoginView;
//@property (nonatomic, strong)DKLoginPhoneView * dk_LoginPhoneView;
@property (nonatomic, strong)UIButton * dk_LoginNextBtn;
@property (nonatomic, strong)UIButton * dk_RegisterAgreementBtn;

@property (nonatomic, strong)DKLoginAgreementAlertView * dk_LoginAgreementAlertView;
@property (nonatomic, strong)zhPopupController * sureAgreemnetCtrl;
@end

@implementation DKLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    // Do any additional setup after loading the view.
    [self dk_creatView];
    [self showSureAgreemnetView];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestUserBrhavRecord:DK_ActionEnter withParmDic:@{}];
}
- (void)dk_creatView{
    //log名称
    DKLoginRegisterNameView *loginRegisterNameView = [[DKLoginRegisterNameView alloc] init];
    [self.view addSubview:loginRegisterNameView];
    [loginRegisterNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@(DK_IsWidthScale(0)));
        make.top.equalTo(@(DK_IsWidthScale(76)+DK_SafeAreaTop));
        make.height.equalTo(@(DK_IsWidthScale(40)));
    }];
    //登录方式切换
    DKLoginChangeLoginTypeView *dk_LoginChangeLoginTypeView = [[DKLoginChangeLoginTypeView alloc] init];
    [dk_LoginChangeLoginTypeView defaltInit];
    [self.view addSubview:dk_LoginChangeLoginTypeView];
    [dk_LoginChangeLoginTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@(DK_IsWidthScale(0)));
        make.top.equalTo(loginRegisterNameView.mas_bottom).offset(DK_IsWidthScale(30));
        make.height.equalTo(@(DK_IsWidthScale(24)));
    }];
    WeakSelf(self)
    dk_LoginChangeLoginTypeView.changeLoginTypeBlock = ^(int tag) {
        if(tag == 100){//选择密码登录
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.dk_LoginPwdLoginView.alpha = 1;
                weakSelf.dk_LoginCodeLoginView.alpha = 0;
//                weakSelf.dk_LoginPhoneView.alpha = 0;
            }];
            [weakSelf.dk_LoginCodeLoginView clearLogin];
            [weakSelf updataNextStatus];
        }else{//选择验证码登录
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.dk_LoginPwdLoginView.alpha = 0;
                weakSelf.dk_LoginCodeLoginView.alpha = 1;
//                weakSelf.dk_LoginPhoneView.alpha = 0;
            }];
            [weakSelf.dk_LoginPwdLoginView clearLogin];
            [weakSelf updataNextStatus];
        }
    };
    //密码登录
    self.dk_LoginPwdLoginView = [[DKLoginPwdLoginView alloc] init];
    [self.view addSubview:self.dk_LoginPwdLoginView];
    [self.dk_LoginPwdLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@(DK_IsWidthScale(0)));
        make.top.equalTo(dk_LoginChangeLoginTypeView.mas_bottom).offset(DK_IsWidthScale(20));
        make.height.equalTo(@(DK_IsWidthScale(160)));
    }];
    self.dk_LoginPwdLoginView.goAccountForgotPwdBlock = ^{//密码登录页面-》忘记密码
        DKLoginForgetPwdViewController * dk_LoginForgetPwdViewCtlr = [[DKLoginForgetPwdViewController alloc] init];
        [weakSelf.navigationController pushViewController:dk_LoginForgetPwdViewCtlr animated:YES];
    };
    self.dk_LoginPwdLoginView.goAccountRegisterPhoneBlock = ^{//密码登录-》注册账号
        DKRegisterViewController * dk_RegisterViewCtrl = [[DKRegisterViewController alloc] init];
        [weakSelf.navigationController pushViewController:dk_RegisterViewCtrl animated:YES];
    };
    self.dk_LoginPwdLoginView.goCheckLoginPwdBlock = ^(BOOL isPhoneNull) {//是否都输入完成
        [weakSelf updataNextStatus];
    };
    //验证码登录
    self.dk_LoginCodeLoginView = [[DKLoginCodeLoginView alloc] init];
    self.dk_LoginCodeLoginView.smsType = @"login";
    self.dk_LoginCodeLoginView.alpha = 0;
    [self.view addSubview:self.dk_LoginCodeLoginView];
    [self.dk_LoginCodeLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@(DK_IsWidthScale(0)));
        make.top.equalTo(dk_LoginChangeLoginTypeView.mas_bottom).offset(DK_IsWidthScale(20));
        make.height.equalTo(@(DK_IsWidthScale(160)));
    }];
    self.dk_LoginCodeLoginView.goCheckLoginCodeBlock = ^(BOOL isPhoneNull) {//是否都输入完成
        [weakSelf updataNextStatus];
    };
//    self.dk_LoginCodeLoginView.goAccountResetBlock = ^{
//        [UIView animateWithDuration:0.5 animations:^{
//            weakSelf.dk_LoginPhoneView.alpha = 1;
//            weakSelf.dk_LoginCodeLoginView.alpha = 0;
//        }];
//    };
//    //重新选手机号
//    self.dk_LoginPhoneView = [[DKLoginPhoneView alloc] init];
//    self.dk_LoginPhoneView.loginPlace = @"Please enter your phone number";
//    self.dk_LoginPhoneView.alpha = 0;
//    [self.view addSubview:self.dk_LoginPhoneView];
//    [self.dk_LoginPhoneView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(@(DK_IsWidthScale(30)));
//        make.right.equalTo(@(-DK_IsWidthScale(30)));
//        make.top.equalTo(dk_LoginChangeLoginTypeView.mas_bottom).offset(DK_IsWidthScale(20));
//        make.height.equalTo(@(DK_IsWidthScale(50)));
//    }];
    
    //协议
    self.dk_RegisterAgreementBtn = [[UIButton alloc] init];
    [self.dk_RegisterAgreementBtn setBackgroundImage:[UIImage imageNamed:@"dk_register_noSelect"] forState:UIControlStateNormal];
    [self.dk_RegisterAgreementBtn setBackgroundImage:[UIImage imageNamed:@"dk_register_Select"] forState:UIControlStateSelected];
    [self.dk_RegisterAgreementBtn addTarget:self action:@selector(goAgreeAgreenment:) forControlEvents:UIControlEventTouchUpInside];
    self.dk_RegisterAgreementBtn.selected = YES;
    [self.view addSubview:self.dk_RegisterAgreementBtn];
    [self.dk_RegisterAgreementBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(DK_IsWidthScale(36)));
        make.width.equalTo(@(DK_IsWidthScale(16)));
        make.height.equalTo(@(DK_IsWidthScale(16)));
        make.bottom.equalTo(@(-DK_IsWidthScale(77)-DK_SafeAreaBottom));
    }];
    TTTAttributedLabel * dk_RegisterAgreementLab = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
    dk_RegisterAgreementLab.numberOfLines = 0;
    [self.view addSubview:dk_RegisterAgreementLab];
    [dk_RegisterAgreementLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dk_RegisterAgreementBtn.mas_right).offset(DK_IsWidthScale(6));
        make.right.equalTo(@(-DK_IsWidthScale(30)));
        make.top.equalTo(self.dk_RegisterAgreementBtn.mas_top).offset(-DK_IsWidthScale(1));
    }];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"Account login is deemed to agree with the《Privacy Agreement》and the 《Registration Agreement》"];
    [attStr addAttribute:NSFontAttributeName value:DK_FONT_Regular(12) range:NSMakeRange(0,attStr.length)];
    [attStr addAttribute:NSForegroundColorAttributeName value:DK_Hex(@"#333333") range:NSMakeRange(0,attStr.length)];
    [attStr addAttribute:NSForegroundColorAttributeName value:DK_Hex(@"#4566FF") range:NSMakeRange(41,19)];
    [attStr addAttribute:NSForegroundColorAttributeName value:DK_Hex(@"#4566FF") range:NSMakeRange(68,attStr.length-68)];
    dk_RegisterAgreementLab.delegate = self;
    dk_RegisterAgreementLab.attributedText = attStr;
    dk_RegisterAgreementLab.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    dk_RegisterAgreementLab.linkAttributes = @{NSForegroundColorAttributeName:DK_Hex(@"#4566FF")};
    [dk_RegisterAgreementLab addLinkToURL:[NSURL URLWithString:DK_PrivacyAgreement] withRange:NSMakeRange(41,19)];
    [dk_RegisterAgreementLab addLinkToURL:[NSURL URLWithString:DK_RegisterAgreement] withRange:NSMakeRange(68,attStr.length-68)];
    //next
    self.dk_LoginNextBtn = [[UIButton alloc] init];
    [self.dk_LoginNextBtn setTitle:@"Next" forState:UIControlStateNormal];
    [self.dk_LoginNextBtn setTitleColor:DK_Hex(@"#4566FF") forState:UIControlStateNormal];
    [self.dk_LoginNextBtn setTitleColor:DK_Hex(@"#FFFFFF") forState:UIControlStateSelected];
    self.dk_LoginNextBtn.titleLabel.font = DK_FONT_Semibold(16);
    [self.dk_LoginNextBtn setBackgroundImage:DK_GetImage(@"dk_registerNextBg") forState:UIControlStateNormal];
    [self.dk_LoginNextBtn setBackgroundImage:DK_GetImage(@"dk_registerNextSelectBg") forState:UIControlStateSelected];
    [self.dk_LoginNextBtn addTarget:self action:@selector(goLogin) forControlEvents:UIControlEventTouchUpInside];
    self.dk_LoginNextBtn.userInteractionEnabled = false;
    [self.view addSubview:self.dk_LoginNextBtn];
    [self.dk_LoginNextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(DK_IsWidthScale(30)));
        make.right.equalTo(@(-DK_IsWidthScale(30)));
        make.height.equalTo(@(DK_IsWidthScale(50)));
        make.bottom.equalTo(dk_RegisterAgreementLab.mas_top).offset(-DK_IsWidthScale(100));
    }];
}
- (void)showSureAgreemnetView{
    WeakSelf(self)
    [DKLoginAgreementAlertView dk_ShowLoginAgreementAlertViewNext:self.view Complete:^{
        
    } WithGoUrl:^(NSString * _Nonnull url) {
//        DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] init];
//        dk_WebViewCtrl.webUrl = url;
        DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] initWithUrl:url withIsNavBar:YES];
        [weakSelf.navigationController pushViewController:dk_WebViewCtrl animated:YES];
    }];
}
//选择协议
- (void)goAgreeAgreenment:(UIButton *)sender{
    sender.selected = !sender.isSelected;
    [self updataNextStatus];
//    self.dk_LoginNextBtn.selected = sender.isSelected;
}
- (void)updataNextStatus{
    if(self.dk_LoginPwdLoginView.alpha == 1){//密码登录
        NSString * account = [self.dk_LoginPwdLoginView getLoginPhone];
        NSString * pwd = [self.dk_LoginPwdLoginView getLoginPwd];
        if(account.length&&pwd.length&&self.dk_RegisterAgreementBtn.isSelected){
            self.dk_LoginNextBtn.selected = YES;
            self.dk_LoginNextBtn.userInteractionEnabled = YES;
        }else{
            self.dk_LoginNextBtn.selected = NO;
            self.dk_LoginNextBtn.userInteractionEnabled = NO;
        }
    }else if (self.dk_LoginCodeLoginView.alpha == 1){//验证码登录
        NSString * account = [self.dk_LoginCodeLoginView getLoginPhone];
        NSString * code = [self.dk_LoginCodeLoginView getLoginCode];
        if(account.length&&code.length&&self.dk_RegisterAgreementBtn.isSelected){
            self.dk_LoginNextBtn.selected = YES;
            self.dk_LoginNextBtn.userInteractionEnabled = YES;
        }else{
            self.dk_LoginNextBtn.selected = NO;
            self.dk_LoginNextBtn.userInteractionEnabled = NO;
        }
    }
}
- (void)goLogin{
    [self requestUserBrhavRecord:DK_ActionClick withParmDic:@{}];

    WeakSelf(self)
    if(self.dk_LoginPwdLoginView.alpha == 1){//密码登录
        if([self.dk_LoginPwdLoginView getLoginPhone].length <= 0){
//            [DKAlertHelper showMessage:@"Please enter your phone number"];
            return;
        }
        if([self.dk_LoginPwdLoginView getLoginPwd].length <= 0){
//            [DKAlertHelper showMessage:@"Please enter your password"];
            return;
        }
        NSMutableDictionary *loginPhoneDic = [[NSMutableDictionary alloc] init];
        [loginPhoneDic setValue:[self.dk_LoginPwdLoginView getLoginPhone] forKey:@"loginName"];
        [loginPhoneDic setValue:@"PWD" forKey:@"loginType"];
        if([[DKGlobalHelper defaultManager] getUserRsaKey].length > 0){
            NSLog(@"密码:%@",[self.dk_LoginPwdLoginView getLoginPwd]);
            NSLog(@"公钥:%@",[DKGlobalHelper defaultManager].userRsaKey);
            NSLog(@"公钥加密：%@",[IPNRSAUtil encryptString:[self.dk_LoginPwdLoginView getLoginPwd] publicKey:[DKGlobalHelper defaultManager].userRsaKey]);
            [loginPhoneDic setValue:[IPNRSAUtil encryptString:[self.dk_LoginPwdLoginView getLoginPwd] publicKey:[DKGlobalHelper defaultManager].userRsaKey] forKey:@"pwd"];
            [self sendLoginRequest:loginPhoneDic];
        }else{
            [DKPublicHttp apiUserRsaKeyForAPI:@{} complete:^{
                NSLog(@"公钥加密：%@",[IPNRSAUtil encryptString:[weakSelf.dk_LoginPwdLoginView getLoginPwd] publicKey:[DKGlobalHelper defaultManager].userRsaKey]);
                [loginPhoneDic setValue:[IPNRSAUtil encryptString:[weakSelf.dk_LoginPwdLoginView getLoginPwd] publicKey:[DKGlobalHelper defaultManager].userRsaKey] forKey:@"pwd"];
                [weakSelf sendLoginRequest:loginPhoneDic];
            }];
        }
    }else if (self.dk_LoginCodeLoginView.alpha == 1){//验证码登录
        if([self.dk_LoginCodeLoginView getLoginPhone].length <= 0){
//            [DKAlertHelper showMessage:@"Please enter your phone number"];
            return;
        }
        if([self.dk_LoginCodeLoginView getLoginCode].length <= 0){
//            [DKAlertHelper showMessage:@"Please enter your phone code"];
            return;
        }
        NSMutableDictionary *loginPhoneSmsDic = [[NSMutableDictionary alloc] init];
        [loginPhoneSmsDic setValue:[self.dk_LoginCodeLoginView getLoginPhone] forKey:@"loginName"];
        [loginPhoneSmsDic setValue:@"SMS" forKey:@"loginType"];
        [loginPhoneSmsDic setValue:[self.dk_LoginCodeLoginView getLoginCode] forKey:@"vcode"];
        [self sendLoginRequest:loginPhoneSmsDic];
    }
//    if(self.dk_LoginPhoneView.alpha == 1){//重新选号
//        [UIView animateWithDuration:0.5 animations:^{
//            weakSelf.dk_LoginPhoneView.alpha = 0;
//            weakSelf.dk_LoginCodeLoginView.alpha = 1;
//            weakSelf.dk_LoginCodeLoginView.dk_LoginAccountView.dk_LoginAccountTextField.text = [weakSelf.dk_LoginPhoneView getLoginPhone];
//        }];
//        return;
//    }
}
- (void)sendLoginRequest:(NSDictionary *)parmDic{
    WeakSelf(self)
    [DKULoginHttp apiUserLoginForAPI:parmDic complete:^{
        DKTabBarViewController * dk_TabBarViewCtrl = [[DKTabBarViewController alloc] init];
        dk_TabBarViewCtrl.isAuth = YES;//默认未认证，未认证会再次识别
        ((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController = dk_TabBarViewCtrl;
        
        [weakSelf requestUserBrhavRecord:DK_ActionSave withParmDic:@{}];
    }];
}
- (void)requestUserBrhavRecord:(NSString *)action withParmDic:(NSDictionary *)parmDic{
    [DKPublicHttp apiUserBrhavRecordForAPI:parmDic withPageName:DK_Login withAction:action complete:^{
            
    } fail:^{
            
    }];
}
#pragma mark -- TTTAttributedLabelDelegate
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
//    DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] init];
//    dk_WebViewCtrl.webUrl = url.absoluteString;
    DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] initWithUrl:url.absoluteString withIsNavBar:YES];
    [self.navigationController pushViewController:dk_WebViewCtrl animated:YES];
}
@end
